<template>
  <view class="container">
    <!-- Tab栏 -->
    <view class="bottom-tab">
      <view :class="classNameArr[0]" @click="changeTab(0)">进行中</view>
      <view :class="classNameArr[1]" @click="changeTab(1)">已完成</view>
    </view>
    <!-- 任务列表 -->
    <view class="task-list">
      <!-- 使用 uni-swipe-action 包裹每个 task-item -->
      <uni-swipe-action v-for="task in tasks" :key="task.id">
        <uni-swipe-action-item>
          <!-- 左滑时显示的操作按钮 -->
          <template v-slot:right>
            <view class="swipe-buttons">
              <button @click="handleComplete(task.id)" class="complete-btn" v-if="task.status == 0">完成</button>
              <button @click="handleEdit(task)" class="edit-btn">编辑</button>
              <button @click="handleDelete(task.id)" class="delete-btn">删除</button>
            </view>
          </template>
          <!-- 正常的 task-item 内容 -->
          <view class="task-item">
            <view class="task-time">更新时间: {{ task.updateTime }}</view>
            <text class="task-title">{{ task.title }}</text>
            <view class="task-priority" :class="getPriorityClass(task.priority)">
              {{ getPriorityLabel(task.priority) }}
            </view>
          </view>
        </uni-swipe-action-item>
      </uni-swipe-action>
    </view>
    <view class="floating-button" :style="{ left: `${position.left}px`, top: `${position.top}px` }"
      @touchstart="onTouchStart" @touchmove="onTouchMove" @touchend="onTouchEnd" @click="openTaskPopup">
      <view class="plus-icon">+</view>
    </view>
    <!-- 添加任务的弹窗 -->
    <uni-popup ref="taskPopup" :show="showPopup" @close="showPopup = false">
      <view class="popup-content">
        <view class="form">
          <!-- 任务标题输入 -->
          <view class="form-item">
            <view class="form-label">任务标题:</view>
            <input v-model="newTask.title" placeholder="请输入任务标题" class="task-input" />
          </view>
          <!-- 优先级输入 -->
          <view class="form-item">
            <view class="form-label">当前优先级:</view>
            <input v-model="newTask.priority" placeholder="请输入优先级 (1-9)" class="task-input" />
          </view>
          <!-- 优先级选择 -->
          <view class="priority-section">
            <view class="form-label">选择优先级:</view>
            <view class="priority-options">
              <view v-for="i in 9" :key="i" class="priority-option" :class="getPriorityClass(i)"
                @click="newTask.priority = i">
                {{ i }}
              </view>
            </view>
          </view>
          <!-- 按钮组 -->
          <view class="button-group">
            <button @click="addTask" class="add-button">完成</button>
            <button @click="closeTaskPopup" class="cancel-button">取消</button>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, defineProps, onMounted } from 'vue';
import UniPopup from '../uni_modules/uni-popup/components/uni-popup/uni-popup.vue';
import UniSwipeAction from '../uni_modules/uni-swipe-action/components/uni-swipe-action/uni-swipe-action.vue'
import uniSwipeActionItem from '../uni_modules/uni-swipe-action/components/uni-swipe-action-item/uni-swipe-action-item.vue'
import { commonPlanAdd, commonPlanDelete, commonPlanList, commonPlanUpdate, commonPlanUpdateStatus } from '@/api/commonPlan/commonPlan';
const props = defineProps<{
  type: string; // 必传参数
}>();
interface Task {
  id?: number;          // 可选字段
  uid?: number;         // 可选字段
  title?: string;       // 可选字段
  updateTime?: string;  // 可选字段
  priority?: number;    // 可选字段
  status?: number;      // 可选字段
  type?: number;      // 可选字段
}

// Tab栏状态
const tabNumNow = ref(0); // 当前选中的Tab索引
const tabs = ['Tab1', 'Tab2', 'Tab3', 'Tab4']; // Tab栏的标题
const classNameArr = ref<string[]>([]); // Tab栏的类名数组
const initTabs = () => {
  classNameArr.value = tabs.map((_, index) =>
    index === tabNumNow.value ? 'tab-item-active' : 'tab-item-default'
  );
};
initTabs(); // 初始化
const changeTab = (tabNum: number) => {
  tabNumNow.value = tabNum;
  classNameArr.value = tabs.map((_, index) =>
    index === tabNumNow.value ? 'tab-item-active' : 'tab-item-default'
  );
  init();
};

// 任务列表
const tasks = ref<Task[]>()
const init = async()=>{
  const res = await commonPlanList(Number.parseInt(props.type),tabNumNow.value );
  console.log("任务列表: ", res);
  tasks.value = res.data;
}
onMounted(() => {
  init()
})
 
// 表单弹窗相关
const showPopup = ref(false);
const taskPopup = ref(null);
const openTaskPopup = () => {
  console.log("点击")
  console.log(taskPopup.value)
  if (taskPopup.value) {
    showPopup.value = true
    taskPopup.value.open("taskPopup")
  }
}

interface NewTask {
  title: string;
  priority: number;
}
// 任务表单数据
const newTask = ref<NewTask>({
  title: '',
  priority: 1,
});
const closeTaskPopup = () => {
  if (taskPopup.value) {
    showPopup.value = false;
    taskPopup.value.close();
  }
  newTask.value.title = '';
  newTask.value.priority = 1;
  currentUpdateId.value = null;
}
// 添加任务
const addTask = async () => {
  if (newTask.value.title.trim() === '') {
    uni.showToast({
      title: '任务标题不能为空',
      icon: 'none',
    });
    return;
  }
  const newTask2:Task = {
    title: newTask.value.title,
    status: 0,
    priority: newTask.value.priority,
    type: Number.parseInt(props.type)
  }
  // 发送一个请求, 用于保存
  if(currentUpdateId.value === null){
    // 就是新增
    await commonPlanAdd(newTask2);
  }else{
    // 就是修改
    newTask2.id = currentUpdateId.value;
    await commonPlanUpdate(newTask2)
  }
  const res = await commonPlanList(Number.parseInt(props.type), tabNumNow.value);
  console.log("res: ",res);
  tasks.value = res.data;
  setTimeout(()=>{
    closeTaskPopup();
  },500);
};

// 获取优先级标签
const getPriorityLabel = (priority: number) => {
  if (priority >= 1 && priority <= 3) return '低优先级';
  if (priority >= 4 && priority <= 6) return '中优先级';
  if (priority >= 7 && priority <= 9) return '高优先级';
  return '未知';
};

// 获取优先级类名
const getPriorityClass = (priority: number) => {
  if (priority >= 1 && priority <= 3) return 'priority-low';
  if (priority >= 4 && priority <= 6) return 'priority-medium';
  if (priority >= 7 && priority <= 9) return 'priority-high';
  return '';
};

// 可移动按钮
const position = ref({ left: uni.getSystemInfoSync().screenWidth - 70, top: uni.getSystemInfoSync().screenHeight - 140 });
const startTouch = ref({ x: 0, y: 0 });
const isDragging = ref(false);
const onTouchStart = (event: TouchEvent) => {
  const touch = event.touches[0];
  startTouch.value = {
    x: touch.clientX - position.value.left,
    y: touch.clientY - position.value.top,
  };
  isDragging.value = true;
};
const onTouchMove = (event: TouchEvent) => {
  if (!isDragging.value) return;
  const touch = event.touches[0];
  const newLeft = touch.clientX - startTouch.value.x;
  const newTop = touch.clientY - startTouch.value.y;
  const systemInfo = uni.getSystemInfoSync();
  const maxLeft = systemInfo.screenWidth - 50;
  const maxTop = systemInfo.screenHeight - 100; // 按钮高度假设为 50px
  position.value.left = Math.max(0, Math.min(newLeft, maxLeft));
  position.value.top = Math.max(0, Math.min(newTop, maxTop));
};
const onTouchEnd = () => {
  isDragging.value = false;
};

// 列表元素左滑
const handleComplete = async (taskId: number) => {
  console.log('完成任务:', taskId);
  await commonPlanUpdateStatus(taskId);
  init();
};

const currentUpdateId = ref(null);
const handleEdit = (task: Task) => {
  console.log('编辑任务:', task);
  newTask.value.title = task.title;
  newTask.value.priority = task.priority;
  currentUpdateId.value = task.id;
  openTaskPopup()
};
const handleDelete = async (taskId: number) => {
  console.log('删除任务:', taskId);
  await commonPlanDelete(taskId);
  init();
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: flex-start;
  text-align: center;
  height: 98vh;
  padding: 1vh 20px;
  background-color: #fff;
}

.bottom-tab {
  display: flex;
  justify-content: space-around;
  background-color: rgba(255, 255, 255, 0);
  /* 白色，但透明度为0，即完全透明 */
  padding: 10px 0;
  height: 30px;
  width: 90vw;
  border-top: 1px solid #eee;
  text-align: center;
}

.tab-item-default {
  font-size: 14px;
  color: #4c88ad;
  height: 100%;
  width: 25%;
  opacity: 0.5;
}

.tab-item-active {
  font-size: 14px;
  height: 100%;
  width: 25%;

  color: #4c88ad;
}

.task-list {
  margin-top: 10px;
  padding: 10px;
  width: 96%;
  border: 1px solid #ddd;
  border-radius: 8px;
  /* background-color: #f9f9f9; */
  overflow-y: scroll;
}

.task-item {
  position: relative;
  display: flex;
  padding: 10px;
  margin-bottom: 10px;
  height: 40px;
  border-bottom: 1px solid #eee;
  border-radius: 10px;
  border: 1px solid #ddd;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.task-time {
  position: absolute;
  left: 10px;
  bottom: 10px;
  font-size: 10px;
  color: rgba(82, 74, 74, 0.5);
}

.task-title {
  font-size: 14px;
  margin-top: 8px;
}

.task-priority {
  position: absolute;
  right: 10px;
  bottom: 10px;
  font-size: 12px;
  padding: 2px 6px;
  border-radius: 4px;
  color: white;
  animation: fadeIn 0.5s ease-in-out;
}

.priority-low {
  background-color: #4CAF50;
}

.priority-medium {
  background-color: #FFC107;
}

.priority-high {
  background-color: #F44336;
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

.floating-button {
  position: fixed;
  bottom: 20px;
  right: 20px;
  width: 50px;
  height: 50px;
  background-color: #007AFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 24px;
  cursor: pointer;
}

.popup-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 10px;
  width: 300px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.task-input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
}

.priority-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.priority-label {
  font-size: 14px;
  color: #333;
}

.priority-options {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.priority-option {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #eee;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.priority-option:hover {
  background-color: #ddd;
}

.priority-option.priority-low {
  background-color: #4CAF50;
  color: white;
}

.priority-option.priority-medium {
  background-color: #FFC107;
  color: white;
}

.priority-option.priority-high {
  background-color: #F44336;
  color: white;
}

.button-group {
  display: flex;
  justify-content: space-between;
  gap: 10px;
}

.add-button {
  background-color: #4CAF50;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
}

.cancel-button {
  background-color: #f44336;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
}

.add-button:hover,
.cancel-button:hover {
  opacity: 0.9;
}

.floating-button {
  position: fixed;
  right: 10px;
  bottom: 10px;
  width: 50px;
  height: 50px;
  background-color: #007aff;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  z-index: 9999;
}

.plus-icon {
  color: white;
  font-size: 24px;
  font-weight: bold;
}

.swipe-buttons {
  display: flex;
  align-items: center;
  /* height: 100%; */
}

.complete-btn,
.edit-btn,
.delete-btn {
  /* margin: 10px; */
  border-radius: 0;
  background-color: #4CAF50;
  /* 完成按钮背景色 */
  color: white;
  border-radius: 10px;
  font-size: small;
  padding: 2vw;
}
.edit-btn {
  background-color: #FFC107;
  /* 编辑按钮背景色 */
}

.delete-btn {
  background-color: #F44336;
  /* 删除按钮背景色 */
}

.popup-content {
  background-color: #ffffff;
  padding: 20px;
  border-radius: 10px;
  width: 300px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.form {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.form-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.form-label {
  font-size: 14px;
  color: #333;
  font-weight: bold;
}

.task-input {
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  font-size: 14px;
}

.priority-section {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.priority-options {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
}

.priority-option {
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  background-color: #eee;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.priority-option:hover {
  background-color: #ddd;
}

.priority-option.priority-low {
  background-color: #4CAF50;
  color: white;
}

.priority-option.priority-medium {
  background-color: #FFC107;
  color: white;
}

.priority-option.priority-high {
  background-color: #F44336;
  color: white;
}

.button-group {
  display: flex;
  justify-content: space-between;
  gap: 10px;
  margin-top: 15px;
}

.add-button,
.cancel-button {
  flex: 1;
  padding: 8px 12px;
  border: none;
  border-radius: 5px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.add-button {
  background-color: #007AFF;
  /* 商务蓝色 */
  color: white;
}

.cancel-button {
  background-color: #6c757d;
  /* 灰色 */
  color: white;
}

.add-button:hover {
  background-color: #005bb5;
  /* 深蓝色 */
}

.cancel-button:hover {
  background-color: #5a6268;
  /* 深灰色 */
}
</style>